import serial

class SerialTemperatureReader:
    def __init__(self, port='/dev/ttyS0', baudrate=115200):
        self.ser = None
        self.port = port
        self.baudrate = baudrate
        self.connected = False
        
    def connect(self):
        try:
            self.ser = serial.Serial(
                port=self.port,
                baudrate=self.baudrate,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=0.1
            )
            self.connected = True
            print(f"[INFO] 串口 {self.port} 连接成功")
            return True
        except Exception as e:
            print(f"[ERROR] 串口连接失败: {e}")
            self.connected = False
            return False
    
    def parse_temperature_data(self, data_bytes):
        if len(data_bytes) != 6:
            return None
        
        # 检查包头和包尾
        if data_bytes[0] != 0xFA:
            return None
        
        if data_bytes[4] != 0xEB or data_bytes[5] != 0x90:
            return None
        
        # 解析温度数据
        temp_integer = data_bytes[1]        # 整数部分
        temp_fraction_byte = data_bytes[2]  # 小数部分字节
        
        # 解析正负号 (bit7)
        is_negative = (temp_fraction_byte & 0x80) >> 7
        sign = -1 if is_negative else 1
        
        # 解析小数部分 (低7位)
        fraction_raw = temp_fraction_byte & 0x7F
        fraction = fraction_raw / 100.0
        
        # 计算最终温度值
        temperature = sign * (temp_integer + fraction)
        
        # 蓝牙模块地址
        bluetooth_addr = data_bytes[3]
        
        return temperature
    
    def read_temperature(self):
        if not self.connected or self.ser is None:
            return None
        
        try:
            # 读取6字节数据
            data = self.ser.read(6)
            
            if len(data) == 6:
                temperature = self.parse_temperature_data(data)
                if temperature is not None:
                    return temperature

            return None
                
        except Exception as e:
            print(f"[ERROR] 读取串口数据失败: {e}")
            return None
    
    def release(self):
        if self.ser and self.connected:
            self.ser.close()
            self.connected = False
            print("[INFO] 串口连接已关闭")
